const express = require('express');
const bodyParser = require('body-parser');
const cors = require('cors');
const path = require('path');
const sequelize = require("./config/database");

const authRoutes = require('./routes/auth');
const fileRoutes = require('./routes/file');
const userRoutes = require('./routes/user');
const courseRoutes = require('./routes/course');
const tagsRoutes = require('./routes/tags');
const issueRoutes = require('./routes/issue');
const categoryRoutes = require('./routes/category');
const articleRoutes = require('./routes/article');
const commentRoutes = require('./routes/comment');

// 导入鉴权中间件
const authMiddleware = require('./middleware/authMiddleware');

// 导入日志配置
const log = require('./config/logConfig.js')
const app = express()
// 解析post body x-www-form-urlencoed格式数据
app.use(bodyParser.urlencoded({ extended: false }))

// 用来解析 post body json 格式数据
app.use(bodyParser.json());
// 处理跨域(浏览器的同源策略)
app.use(cors());
app.use("/tempFiles", express.static(path.join(__dirname, "tempFiles")));
// 记录日志
log.use(app)

//路由
app.use('/auth', authRoutes) // 除了登录、注册不走鉴权中间件 其余都走
app.use(authMiddleware);
app.use('/upload', fileRoutes)
app.use('/user',userRoutes)
app.use('/course',courseRoutes)
app.use('/tags',tagsRoutes)
app.use('/issue',issueRoutes)
app.use('/category',categoryRoutes)
app.use('/article',articleRoutes)
app.use('/article/comment',commentRoutes)
// 数据库同步
sequelize
  .sync()
  .then(() => {
    console.log("Database synced");
  })
  .catch((error) => {
    console.error("Error syncing database:", error);
  });

// 启动服务器
const port = process.env.PORT || 8032;
app.listen(port, () => {
  console.log(`Server is running on port ${port}`);
});
